package com.example.paypallesson01.controller;

import com.example.paypallesson01.model.PaymentEx;
import com.example.paypallesson01.model.ShopOrderItemEx;
import com.example.paypallesson01.model.ShopOrderPayment;
import com.example.paypallesson01.service.PayDemoService;
import com.example.paypallesson01.utils.URLUtils;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/07/19
 * @Description:
 */
@Controller
@RequestMapping("/")
public class Pay1Controller {
    public static final  String PAYPAL_SUCCESS_URL = "paypal/successPay";
    public static final  String PAYPAL_CANCEL_URL = "paypal/cancelPay";
    private static String FAIL_URL = "https://www.baidu.com";

    @Autowired
    private PayDemoService payDemoService;

    private Logger log = LoggerFactory.getLogger(getClass());
    private static Integer orderId = null;


//    @RequestMapping(method = RequestMethod.GET)
//    public String index(){
//        return "index";
//    }

    /**
     * 订单支付
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/payment")
    public String payment(HttpServletRequest request)throws Exception{

        /**
         * 注意: subTotal = Price*Quantity
         * total = Tax+shipping+subTotal
         */
        PaymentEx paymentEx = new PaymentEx();
        paymentEx.setAddress("天津市东丽区华明镇");
        paymentEx.setCancelUrl(PAYPAL_CANCEL_URL);
        paymentEx.setSuccessUrl(PAYPAL_SUCCESS_URL);
        paymentEx.setDescription("iPhone是苹果公司（Apple Inc. ）发布搭载iOS操作系统的系列手机。\n" +
                "截至2021年4月，苹果公司（Apple Inc. ）已发布24款手机产品，初代：iPhone [1]  ，" +
                "最新版本：iPhone 12 mini，iPhone 12，iPhone 12 Pro， iPhone 12 Pro Max [18]  ；" +
                "iPhone系列产品静音键在设备正面的左侧 [46-47]  ；iPhone 5之前机型使用30Pin（即30针）接口，" +
                "iPhone 5（包含）之后产品使用Lightning接口 [49]  。iPhone X之前机型配置Home键；iPhone X（包含）" +
                "之后机型取消了实体Home键 [55]  。\n" +
                "iPhone系列机型自iPhone 4之后配置Apple Silicon自研芯片 [52]  。" +
                "Touch ID在iPhone 5s上首次出现 [48]  ；iPhone 6s 和iPhone 6s Plus首次在屏幕上加入了3D " +
                "Touch压力感应触控 [69]  ；无线充电在iPhone8、iPhone 8 Plus机型首次出现，采用Qi（Chee）无线充电标准 [51]  ");
        Random random = new Random();
        Integer randomInt = random.nextInt(100000000);
        paymentEx.setOrderId(randomInt);
        paymentEx.setTax("10");
        paymentEx.setSubTotal("1000");
        paymentEx.setOrderTotal("1010");

        //创建商品明细
        List<ShopOrderItemEx> list = new ArrayList<>();
        ShopOrderItemEx orderItem = new ShopOrderItemEx();
        orderItem.setQtyOrder("1");
        orderItem.setPrise("1000");
        orderItem.setShortName("苹果手机");
        list.add(orderItem);

        paymentEx.setOrderItemList(list);

        try {
            String cancelUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;
            String successUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL;
            Payment payment = payDemoService.createPayment(paymentEx, successUrl,cancelUrl);
            for(Links links : payment.getLinks()){
                if(links.getRel().equals("approval_url")){
                    // 客户付款登陆地址
                    return "redirect:" + links.getHref();
                }
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
            return "redirect:" + FAIL_URL;
        }
        return "redirect:" + FAIL_URL;
    }

    /**
     * 取消支付
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL)
    public String cancelPay(){
        return "redirect:" + PAYPAL_CANCEL_URL;
    }

    /**
     * 支付成功
     * @param paymentId
     * @param payerId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL)
    public String successPay(@RequestParam("paymentId") String paymentId,
                             @RequestParam("PayerID") String payerId)throws Exception{
        try {
            /**
             * 支付
             */
            Payment payment = payDemoService.executePayment(paymentId, payerId);

            /**
             * 保存支付信息
             */
            ShopOrderPayment orderPayment = new ShopOrderPayment();
            orderPayment.setOrderId(orderId);
            // 订单总价
            String total = payment.getTransactions().get(0).getAmount().getTotal();
            orderPayment.setAmountPaid(new BigDecimal(total));
            // 交易号
            String transationId = payment.getTransactions().get(0).getRelatedResources().get(0).getSale().getId();
            orderPayment.setTransactionId(transationId);
            payDemoService.savePayment(orderPayment);

            /**
             * 支付成功重定向页面
             */
            if(payment.getState().equals("approved")){
                return "success";
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
            return "redirect:" + FAIL_URL;
        }
        return "redirect:" + FAIL_URL;
    }

}
